package com.mani.geotag;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.os.Bundle;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;

public class FaceBookClient {
	
	public interface FaceBookCallBack
	{
		public void onFaceBookAuthenticateCompleted(int response,String token,String username);
		public void onFaceBookmessagePostCompleted(int response);
		public static final int AUTHENTICAION_SUCCESSFULL = 1;
		public static final int AUTHENTICAION_FAILURE = 2;
		public static final int POST_SUCCESSFULL = 1;
		public static final int POST_FAILURE = 2;

	}
	Activity mActivity;
	static FaceBookCallBack mCB;
	
	String mToken;
    private Facebook mFacebook;
    CircularApplication mApp;
    private AsyncFacebookRunner mAsyncRunner;
    public static final String APP_ID = "308222462556405"; // GeoShare app ID.
    public static final String PERMISSION_READ_STREAM		= "read_stream";
    public static final String PERMISSION_PUBLISH_STREAM	= "publish_stream";
    public static final String PERMISSION_READ_MAILBOX		= "read_mailbox";
    public static final String PERMISSION_OFFLINE_ACCESS	= "offline_access";
    private static final String GRAPH_FEED		= "me/feed";
    
    FaceBookClient(Activity context,FaceBookCallBack aCB) 
    {
    	mActivity = context;
    	mCB = aCB;
    	mApp = (CircularApplication) context.getApplication();
    	mFacebook = new Facebook(APP_ID);
       	mAsyncRunner = new AsyncFacebookRunner(mFacebook);
    }
    
    public void setAccessToken(String token)
    {
    	mToken = token;
    }
    
    public void initialize () {
    	if(checkInternetConnection() )
    	{
	    	mFacebook = new Facebook(APP_ID);
	       	mAsyncRunner = new AsyncFacebookRunner(mFacebook);
	       	String[] permissions = {PERMISSION_READ_STREAM, PERMISSION_PUBLISH_STREAM, PERMISSION_READ_MAILBOX, PERMISSION_OFFLINE_ACCESS};
	       	mFacebook.authorize(mActivity, permissions, new LoginDialogListener());
    	}
    	else
    	{
    		//new ErrorDialog(mActivity,"No Internet Connection","Please enable the internet connection",false).show();    		
    	}
    }
    
	private boolean checkInternetConnection() {

		ConnectivityManager conMgr = (ConnectivityManager) mActivity.getSystemService (mActivity.CONNECTIVITY_SERVICE);

		// ARE WE CONNECTED TO THE NET

		if (conMgr.getActiveNetworkInfo() != null
		&& conMgr.getActiveNetworkInfo().isAvailable()
		&& conMgr.getActiveNetworkInfo().isConnected()) {
			return true;
		} else {
			return false;
		}

	} 
    private final class LoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            onAuthenticationComplete(values);
        }

        public void onFacebookError(FacebookError error) {
        	mCB.onFaceBookAuthenticateCompleted(FaceBookCallBack.AUTHENTICAION_FAILURE,null,null);
        	mActivity.finish();
        }
        
        public void onError(DialogError error) {
        	mCB.onFaceBookAuthenticateCompleted(FaceBookCallBack.AUTHENTICAION_FAILURE,null,null);
        	mActivity.finish();
        }

        public void onCancel() {
        	mCB.onFaceBookAuthenticateCompleted(FaceBookCallBack.AUTHENTICAION_FAILURE,null,null);
        	mActivity.finish();
        }
    }
    
    public void onAuthenticationComplete (final Bundle bundle) {
    	mAsyncRunner.request("me", new MyRequestListener());
    }
    
    public class MyRequestListener implements AsyncFacebookRunner.RequestListener
    {
    	public void onComplete(final String response,Object o)
    	{
          	String accessKey = mFacebook.getAccessToken();
        	String userName = null;
        	mFacebook.setAccessExpires(0);
        	mCB.onFaceBookAuthenticateCompleted(FaceBookCallBack.AUTHENTICAION_SUCCESSFULL,accessKey,userName);
        	mApp.updateFacebookToken(accessKey);
        	System.out.println("Access key facebook is "+accessKey);
        	mFacebook.setAccessToken(accessKey);
            try {
                // process the response here: executed in background thread
            	JSONObject json = Util.parseJson(response);
                userName = json.getString("name");
                System.out.println("username is "+userName);
            	//mCB.onFaceBookAuthenticateCompleted(FaceBookCallBack.AUTHENTICAION_SUCCESSFULL,accessKey,userName);
            } catch (JSONException e) {
                System.out.println( "JSON Error in response");
            } catch (FacebookError e) {
                System.out.println("Facebook Error: " + e.getMessage());
            }
  
    	}
    	
        public void onFacebookError(FacebookError e,Object o) {
            //Log.e(TAG, e.getMessage());
        	mCB.onFaceBookAuthenticateCompleted(FaceBookCallBack.AUTHENTICAION_FAILURE,null,null);
            e.printStackTrace();
        }

        public void onFileNotFoundException(FileNotFoundException e,Object o) {
        	mCB.onFaceBookAuthenticateCompleted(FaceBookCallBack.AUTHENTICAION_FAILURE,null,null);
           // Log.e(TAG, e.getMessage());
            e.printStackTrace();
        }

        public void onIOException(IOException e,Object o) {
        	mCB.onFaceBookAuthenticateCompleted(FaceBookCallBack.AUTHENTICAION_FAILURE,null,null);
           // Log.e(TAG, e.getMessage());
            e.printStackTrace();
        }

        public void onMalformedURLException(MalformedURLException e,Object o) {
        	mCB.onFaceBookAuthenticateCompleted(FaceBookCallBack.AUTHENTICAION_FAILURE,null,null);
           // Log.e(TAG, e.getMessage());
            e.printStackTrace();
        }
    }
    public void PostWallMessage(String message,String url,String mapurl) {
    	mFacebook.setAccessExpires(0);
    	mFacebook.setAccessToken(mToken);
    	byte[] data=null;
    	try{
    	Bitmap map = downloadBitmap2x2(mapurl);
    	
    	ByteArrayOutputStream baos = new ByteArrayOutputStream();
    	map.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    	data = baos.toByteArray();
    	
    	}catch(Exception e) {
    		System.out.println("Exception in postwall message ********* ");
    	}  
    	
    	try {
		Bundle args = new Bundle();
    	args.putString("message", message);
    	args.putByteArray("picture", data);
    	args.putString("link", url);
        JSONObject prop2 = new JSONObject();
        prop2.put("text", "You locaiton");
        prop2.put("href", url);
        //args.putString("attachment", prop2.toString());    	
    	mAsyncRunner.request(GRAPH_FEED, args, "POST", new WallMessagePostRequestListener(),null);
    	//mFacebook.dialog(mActivity, "stream.publish", args, new PostPhotoDialogListener());
    	}catch(Exception e) {
    		System.out.println("post to wall failed *************** ");
    	}
	}
    public abstract class BaseDialogListener implements DialogListener {

        public void onFacebookError(FacebookError e) {
            e.printStackTrace();
        }

        public void onError(DialogError e) {
            e.printStackTrace();        
        }

        public void onCancel() {        
        }
        
    }
    public class PostPhotoDialogListener extends BaseDialogListener {

        public void onComplete(Bundle values) {
            final String postId = values.getString("post_id");
            if (postId != null) {
            	System.out.println("Attachement post is successful");
            } else {
               // Log.d("FACEBOOK", "No wall post made");
            }
        }
    }
	public static class WallMessagePostRequestListener extends BaseRequestListener {
        public void onComplete(final String response) {
        		 System.out.println("Wallmessage Response: " + response.toString());
        		 mCB.onFaceBookmessagePostCompleted(FaceBookCallBack.POST_SUCCESSFULL);
        }
    }
	
	public static class BaseRequestListener implements RequestListener {
        public void onComplete(final String response,Object o) {
        	mCB.onFaceBookmessagePostCompleted(FaceBookCallBack.POST_SUCCESSFULL);        	
        }
        
        public void onFacebookError(FacebookError e,Object o) {
        	mCB.onFaceBookmessagePostCompleted(FaceBookCallBack.POST_FAILURE);
        }

        public void onFileNotFoundException(FileNotFoundException e,Object o) {
        	mCB.onFaceBookmessagePostCompleted(FaceBookCallBack.POST_FAILURE); 
        	}

        public void onIOException(IOException e,Object o) {
        	mCB.onFaceBookmessagePostCompleted(FaceBookCallBack.POST_FAILURE); 
        	}

        public void onMalformedURLException(MalformedURLException e,Object o) {
        	mCB.onFaceBookmessagePostCompleted(FaceBookCallBack.POST_FAILURE); 
        	}
    }
	
	Bitmap mMap;
    private Bitmap downloadBitmap2x2(String api) throws IOException {
    	
    	System.out.println("Downoadbitmap is api ******* "+api);
    	URL url=null;
    	URI uri= null;
    	try {
			url = new URL(api);
			uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
    	} catch (URISyntaxException e) {
    		return null;
    	}
    	
        HttpUriRequest request = new HttpGet(uri);
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(request);
 
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            byte[] bytes = EntityUtils.toByteArray(entity);
 
            mMap = BitmapFactory.decodeByteArray(bytes, 0,
                    bytes.length);
            return mMap;
        } else {
            throw new IOException("Download failed, HTTP response code "
                    + statusCode + " - " + statusLine.getReasonPhrase());
        }
    }
 }
